package game.Sprites;

import game.Player.PlayerSkins;
import game.Utils.GraphicsUtils;
import net.sf.image4j.codec.bmp.BMPDecoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.io.InputStream;

public class Transparency {
    /**
     * Converts a given Image into a BufferedImage
     *
     * @param img The Image to be converted
     * @return The converted BufferedImage
     */
    public static BufferedImage toBufferedImage(Image img)
    {
        if (img instanceof BufferedImage)
        {
            return (BufferedImage) img;
        }

        // Create a buffered image with transparency
        BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

        // Draw the image on to the buffered image
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(img, 0, 0, null);
        bGr.dispose();

        // Return the buffered image
        return bimage;
    }

    public static BufferedImage makeColorTransparent
            (Image im, final Color color) {
        ImageFilter filter = new RGBImageFilter() {
            // the color we are looking for... Alpha bits are set to opaque
            public int markerRGB = color.getRGB() | 0xFF000000;

            public final int filterRGB(int x, int y, int rgb) {
                if ( ( rgb | 0xFF000000 ) == markerRGB ) {
                    // Mark the alpha bits as zero - transparent
                    return 0x00FFFFFF & rgb;
                }
                else {
                    // nothing to do
                    return rgb;
                }
            }
        };

        ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
        return toBufferedImage(Toolkit.getDefaultToolkit().createImage(ip));
    }

    public static BufferedImage makeBackgroundTransparent(BufferedImage img){
        int  clr   =  img.getRGB(0,0);
        int  red   = (clr & 0x00ff0000) >> 16;
        int  green = (clr & 0x0000ff00) >> 8;
        int  blue  =  clr & 0x000000ff;

        BufferedImage transpT = Transparency.makeColorTransparent(img, new Color(red,green,blue));
        return transpT;
    }

    public static BufferedImage loadTransparentBMP(InputStream inputStream) throws IOException {
        BufferedImage img = null;
        try {
            img = BMPDecoder.read(inputStream);
            if (img.getTransparency() == 1) {
                // Get transparency from pink background (first pixel)
                img = Transparency.makeBackgroundTransparent(img);
            }
        }catch (Exception ex){
            img = ImageIO.read(inputStream);
            img = Transparency.makeBackgroundTransparent(img);
        }

        return img;
    }

}